package com.jiyinit.web.core.activiti.controller;

import com.jiyinit.core.framework.base.entity.ResponseDto;
import com.jiyinit.core.framework.base.util.Check;
import com.jiyinit.core.framework.base.util.JsonEntityTransform;
import com.jiyinit.core.framework.base.util.LogUtil;
import com.jiyinit.web.core.activiti.dto.*;
import com.jiyinit.web.core.activiti.entity.TabLeaveDealMindEntity;
import com.jiyinit.web.core.activiti.entity.TabUserMemershipEntity;
import com.jiyinit.web.core.activiti.enums.LeaveUserTaskEnum;
import com.jiyinit.web.core.activiti.enums.LvAgreeEnum;
import com.jiyinit.web.core.activiti.enums.ProcessFlowEnum;
import com.jiyinit.web.core.activiti.service.*;
import com.jiyinit.web.core.activiti.vo.LeaveDealMindEntity;
import com.jiyinit.web.core.activiti.vo.NeedDealTaskEntity;
import com.jiyinit.web.core.activiti.entity.TabLeaveBillInfoEntity;
import com.jiyinit.web.core.business.entity.TabCoreOrgEntity;
import com.jiyinit.web.core.business.entity.TabCoreUserEntity;
import com.jiyinit.web.core.business.service.OrgServiceImpl;
import com.jiyinit.web.core.business.service.UserServiceImpl;
import com.jiyinit.web.core.common.util.UserUtil;
import com.jiyinit.web.core.common.vo.LoginUserVo;
import com.jiyinit.web.core.common.vo.MobileUserVo;
import org.activiti.engine.*;
import org.activiti.engine.history.HistoricActivityInstance;
import org.activiti.engine.history.HistoricTaskInstance;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.apache.commons.lang.BooleanUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * <p></p>
 * <p> 待处理清单
 * <PRE>
 * <BR>	修改记录
 * <BR>-----------------------------------------------
 * <BR>	修改日期			修改人			修改内容
 * </PRE>
 *
 * @author jack zh
 * @version 1.0
 * @date 2018/7/19
 * @since 1.0
 */
@Controller
@RequestMapping("/mobile/dealLv")
public class DealContrllor {


    private static Logger logger = LoggerFactory.getLogger(LeaveController.class);


    @Resource(name = "leaveBillInfoServiceImpl")
    private LeaveBillInfoServiceImpl leaveBillInfoService;

    @Resource(name = "leaveDealServiceImpl")
    private LeaveDealServiceImpl leaveDealService;

    @Resource(name = "leaveDealMindServiceImpl")
    private LeaveDealMindServiceImpl leaveDealMindService;

    //节点处理人
    @Resource(name = "userMemershipServiceImpl")
    private UserMemershipServiceImpl userMemershipService;

    @Resource(name = "core.userServiceImpl")
    private UserServiceImpl userService;

    @Resource(name = "activitiServiceImpl")
    ActivitiServiceImpl activitiService;

    //工作流相关
    @Resource(name = "runtimeService")
    RuntimeService runtimeservice;
    @Resource(name = "identityService")
    IdentityService identityservice;
    @Resource(name = "taskService")
    TaskService taskservice;
    @Resource(name = "processEngine")
    ProcessEngine processEngine;

    @Resource(name = "historyService")
    HistoryService historyService;

    @Resource(name = "core.orgServiceImpl")
    OrgServiceImpl orgService;

    /**
     * 我的待办：【查询待处理清单】 逻辑接口  支持分页
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(method = RequestMethod.POST,value = "getNeedTask")//,consumes="application/json", produces="application/json"
    public ResponseEntity<ResponseDto> getNeedTask(HttpServletRequest request, @RequestParam String request_json) {
        String logJson = request.getParameter("request_json");
        LogUtil.info(logger, "接口参数:{}", logJson);
        Map<?, ?> map = JsonEntityTransform.json2Map(logJson);
        String convertStatus = (String) map.get("convertStatus");
        LoginUserVo loginUserVo = (LoginUserVo) JsonEntityTransform.json2Object(logJson, LoginUserVo.class);

        NeedDealTaskRequest dealTaskRequest=new NeedDealTaskRequest();
        dealTaskRequest.setUserId(loginUserVo.getUserId()+"");  //查询节点处理人代办清单
        List<NeedDealTaskEntity> taskList=leaveDealService.getNeedDealTask(dealTaskRequest);
        getConvertStatus(taskList);
        for (NeedDealTaskEntity obj : taskList) {
            obj.setIsDispose("y");
            Integer userId = obj.getUserId();
            Integer orgId = obj.getOrgId();
            TabCoreUserEntity user = getUserInfos(userId);
            obj.setProposerName(user.getUserName());
            TabCoreOrgEntity org = getOrgInfos(orgId);
            obj.setProposerOrgName(org.getOrgName());
        }
        List<NeedDealTaskEntity> dealTasks = leaveDealService.getDealTasksByUserId(loginUserVo.getUserId());
        /*for (NeedDealTaskEntity obj : dealTasks) {
            String isAgree = obj.getIsAgree();
            if("0".equals(isAgree)){
                obj.setConvertStatus("4");//规定4为已拒绝
            }else if("1".equals(isAgree)){
                obj.setConvertStatus("5");//规定5为已同意
            }
        }*/
        taskList.addAll(dealTasks);
        if(!Check.isNullStrStrict(convertStatus)){
            List<NeedDealTaskEntity> newList = new ArrayList<>(taskList.size());
            for (NeedDealTaskEntity obj : taskList) {
                String executionId = obj.getExecutionId();
                String currentUserName = getCurrentUserNameByExecutionId(executionId);
                obj.setCurrentUserName(currentUserName);
                if(convertStatus.equals(obj.getIsAgree())){
                    newList.add(obj);
                }
            }
            return new ResponseEntity<>(ResponseDto.responseOK(newList), HttpStatus.OK);
        }
        for (NeedDealTaskEntity obj : taskList) {
            String executionId = obj.getExecutionId();
            String currentUserName = getCurrentUserNameByExecutionId(executionId);
            obj.setCurrentUserName(currentUserName);
        }
        /*if(!Check.isNullStr(convertStatus)){
            List<NeedDealTaskEntity> newList = new ArrayList<>();
            for (int i = 0; i < taskList.size(); i++) {
                String currentStatus = taskList.get(i).getConvertStatus();
                if(convertStatus.equals(currentStatus)){
                    newList.add(taskList.get(i));
                }
            }
            return new ResponseEntity<>( ResponseDto.responseOK(newList), HttpStatus.OK);
        }*/
        return new ResponseEntity<>( ResponseDto.responseOK(taskList), HttpStatus.OK);
    }


    /**
     * 我的待办 【查询待办任务详情】
     * @param request
     * @param taskid
     * @param request_json
     * @return
     */
    @RequestMapping(method = RequestMethod.POST,value = "taskDetail/{taskid}",consumes="application/json", produces="application/json")
    @ResponseBody
    public ResponseEntity<ResponseDto> taskDetail(HttpServletRequest request, @PathVariable("taskid") String taskid,@RequestParam String request_json){
        String logJson = request.getParameter("request_json");
        LoginUserVo loginUserVo = (LoginUserVo) JsonEntityTransform.json2Object(logJson, LoginUserVo.class);
        LogUtil.info(logger, "接口参数:{}", logJson);

        Task task=taskservice.createTaskQuery().taskId(taskid).taskCandidateOrAssigned(loginUserVo.getUserId()+"").singleResult();
        if(null==task)
        {
            return new ResponseEntity<>(ResponseDto.responseFail("请求非法，稍后再试"), HttpStatus.OK);
        }
        ProcessInstance process=runtimeservice.createProcessInstanceQuery().processInstanceId(task.getProcessInstanceId()).singleResult();
        TabLeaveBillInfoEntity leave=leaveBillInfoService.selectByPrimaryKey(new Integer(process.getBusinessKey()));
        NeedDealTaskEntity needEntity=new NeedDealTaskEntity();
        BeanUtils.copyProperties(leave,needEntity);
        /* 修改区 */
        //needEntity.setTask(task);
        needEntity.setTaskId(task.getId());
        needEntity.setName(task.getName());
        needEntity.setAssignee(task.getAssignee());
        needEntity.setProcessDefinitionId(task.getProcessDefinitionId());
        needEntity.setTaskDefinitionKey(task.getTaskDefinitionKey());
        needEntity.setCreateTime(task.getCreateTime());
        needEntity.setDueDate(task.getDueDate());
        needEntity.setSuspended(task.isSuspended());
        /* 修改区结束 */
        return new ResponseEntity<>( ResponseDto.responseOK(needEntity), HttpStatus.OK);
    }

    /**
     * 我的待办：【处理请假】 逻辑接口
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(method = RequestMethod.POST,value = "taskcomplete")//,consumes="application/json", produces="application/json"
    public ResponseEntity<ResponseDto> taskcomplete(HttpServletRequest request,@RequestParam String request_json) {
        String logJson = request.getParameter("request_json");
        LogUtil.info(logger, "接口参数:{}", logJson);
        if(!Check.isNullStr(logJson)){
            LoginUserVo loginUserVo = (LoginUserVo) JsonEntityTransform.json2Object(logJson, LoginUserVo.class);
            TabLeaveDealMindRequest dealMindRequest = new TabLeaveDealMindRequest();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
            LeaveDealRequest leaveDealRequest = JsonEntityTransform.json2Object(logJson, LeaveDealRequest.class);
            String executionId = leaveDealRequest.getExecutionId();
            String taskId = leaveDealRequest.getTaskId();
            String dealMindInfo = leaveDealRequest.getDealMindInfo();
            boolean isAgree = getIsAgree(leaveDealRequest.getIsAgree());

            dealMindRequest.setExecutionId(executionId);
            dealMindRequest.setTaskId(taskId);
            dealMindRequest.setDealMindInfo(dealMindInfo);
            if(isAgree){
                dealMindRequest.setIsAgree("1");//1代表同意
            }else{
                dealMindRequest.setIsAgree("0");//0为不同意
            }

            //根据token 用户id 获取用户所在部门信息（从session中取）
            MobileUserVo vo= UserUtil.getMobileUser(loginUserVo.getToken());

            if(Check.isNullStr(executionId)){
                return new ResponseEntity<>(ResponseDto.responseFail("无法获取任务id"), HttpStatus.OK);
            }

            if(Check.isNullStr(taskId)){
                return new ResponseEntity<>(ResponseDto.responseFail("无法获取任务id"), HttpStatus.OK);
            }

            if(Check.isNullStr(dealMindInfo)){
                dealMindRequest.setDealMindInfo("");
            }

            if(Check.isNullStr(dealMindRequest.getIsAgree()))
            {
                return new ResponseEntity<>(ResponseDto.responseFail("处理类型为必选项"), HttpStatus.OK);
            }


            //判断当前用户是否是主要负责人
            Task task=taskservice.createTaskQuery().taskId(taskId).taskCandidateOrAssigned(loginUserVo.getUserId()+"").singleResult();
            if(null==task)
            {
                return new ResponseEntity<>(ResponseDto.responseFail("请求非法，稍后再试"), HttpStatus.OK);
            }

            //+++++++++++++++++++++++++++++++++处理原则：存在组关系时 必须是主管领导才可以处理 否则 没有权限；若不存在组关系 且是他自己时 便可以处理自己的单子+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
            TabUserMemershipEntity shipEntity=new TabUserMemershipEntity();
    //        shipEntity.setOrgId(vo.getOrgId());  //部门  先不判断
            shipEntity.setGroupKey(task.getTaskDefinitionKey());
            shipEntity.setProcinstKey(ProcessFlowEnum.Leave.getCode());
            shipEntity.setIsDelete("0");  //未删除
           // shipEntity.setIsMain("1");  //主要负责人
            List<TabUserMemershipEntity> shipList= userMemershipService.findBySelective(shipEntity);
            if(shipList.size()>0)  //存在并且是主管领导
            {
                TabUserMemershipEntity ship=shipList.get(0);
                if(!ship.getIsMain().equals("1"))
                return new ResponseEntity<>(ResponseDto.responseFail("只有主管领导才能处理"), HttpStatus.OK);
            }

            //开始节点处理
            String agreeStr="false";
            if(dealMindRequest.getIsAgree().equals("1")){agreeStr="true";}   //同意请假 其他回退
            Map mapVar=new HashMap();  //同意意见节点变量
            mapVar.put(LvAgreeEnum.getName(task.getTaskDefinitionKey()),agreeStr);


            taskservice.claim(task.getId(),vo.getUserId()+"");  //先拾取

            //如果是最后一个节点  特殊处理（归档时）更新请假记录
            ProcessInstance process=null;
            if(task.getTaskDefinitionKey().equals(LeaveUserTaskEnum.usertask_14.getCode()))
            {
                process=runtimeservice.createProcessInstanceQuery().processInstanceId(task.getProcessInstanceId()).singleResult();
                taskservice.complete(task.getId());
            }else {
                process=runtimeservice.createProcessInstanceQuery().processInstanceId(task.getProcessInstanceId()).singleResult();
                taskservice.complete(task.getId(), mapVar);
            }
            //保存处理意见
            TabLeaveDealMindEntity record=new TabLeaveDealMindEntity();
            BeanUtils.copyProperties(dealMindRequest,record);
            record.setTaskName(task.getName());
            record.setTaskId(task.getId());
            record.setCreateDate(new Date());
            record.setDealUserid(vo.getUserId());
            record.setStatus("1");  //有效
            record.setIsAgree(dealMindRequest.getIsAgree());
            record.setExecutionId(task.getExecutionId());
            leaveDealMindService.insertSelective(record);

            if(agreeStr.equals("false")){
                TabLeaveBillInfoEntity leaveInfo=new TabLeaveBillInfoEntity();
                leaveInfo.setId(new Integer(process.getBusinessKey()));
                leaveInfo.setModDate(new Date());
                leaveInfo.setIsAgree("4");   //将状态设置为拒绝状态
                leaveBillInfoService.updateByPrimaryKeySelective(leaveInfo);
            }
            //如果是最后一个节点  特殊处理（归档时）更新请假记录
            if(task.getTaskDefinitionKey().equals(LeaveUserTaskEnum.usertask_14.getCode()))
            {
                TabLeaveBillInfoEntity leaveInfo=new TabLeaveBillInfoEntity();
                leaveInfo.setId(new Integer(process.getBusinessKey()));
                leaveInfo.setModDate(new Date());
                leaveInfo.setIsAgree("3");   //将状态设置为已备案状态
                leaveBillInfoService.updateByPrimaryKeySelective(leaveInfo);
            }
            return new ResponseEntity<>( ResponseDto.responseOK("任务处理完成"), HttpStatus.OK);
        }
        return new ResponseEntity<>( ResponseDto.responseFail(""), HttpStatus.OK);
     }

     public boolean getIsAgree(String str){
        if(Check.isNullStrStrict(str))throw new NullPointerException("isAgree is null");
        if("true".equals(str) || "false".equals(str)){
            return BooleanUtils.toBoolean(str);
        }else{
            return BooleanUtils.toBoolean(Integer.valueOf(str));
        }
     }

    /**
     * 我的待办 【查询历史处理详情】  不需要分页
     * @param request
     * @param request_json
     * @return
     */
    @RequestMapping(method = RequestMethod.POST,value = "findTaskHis")//,consumes="application/json", produces="application/json"
    @ResponseBody
    public ResponseEntity<ResponseDto> findTaskHis(HttpServletRequest request, @RequestParam String request_json) {
        if(Check.isNullStr(request_json)){
            return new ResponseEntity<ResponseDto>(ResponseDto.responseFail(""), HttpStatus.OK);
        }
        Map<?,?> map = JsonEntityTransform.json2Map(request_json);
        String instanceid = (String) map.get("instanceid");
        if(Check.isNullStr(instanceid)){
            return new ResponseEntity<ResponseDto>(ResponseDto.responseFail("instanceid is null"), HttpStatus.OK);
        }
        List<LeaveDealMindEntity> dealMindList=new ArrayList<>();
        LeaveDealMindEntity dealMind=null;  //处理意见
        TabLeaveDealMindEntity record=null;
        List<TabLeaveDealMindEntity> mindList=null;
        TabCoreUserEntity user=null;
        List<HistoricTaskInstance> his = historyService.createHistoricTaskInstanceQuery().processInstanceId(instanceid).orderByDueDateNullsLast().asc().list();

        for (HistoricTaskInstance task:his) {
              //查询处理意见
            record=new TabLeaveDealMindEntity();
            dealMind=new LeaveDealMindEntity();
            record.setTaskId(task.getId());
            mindList= leaveDealMindService.findBySelective(record);
            if(mindList.size()>0){
                record=mindList.get(0);
                BeanUtils.copyProperties(record,dealMind);
            }
            //查询处理人

            if(!Check.isNullStr(task.getAssignee())) {
                user= userService.getUserInfoByUserId(Integer.parseInt(task.getAssignee()));
                dealMind.setTaskUserName(user.getUserName());  //用户名字
            }
            //添加历史信息
            dealMind.setTaskName(task.getName());
            dealMind.setHisTask(task);
            dealMindList.add(dealMind);
        }

        return new ResponseEntity<>( ResponseDto.responseOK(dealMindList), HttpStatus.OK);
    }

    /**
     * 根据执行实例id 查询所有的历史处理任务节点  （此功能在处理详情页调用）
     * @param request
     * @param instanceid
     * @param request_json
     * @return
     */
    @RequestMapping(method = RequestMethod.POST,value = "findTaskHisByExtId/{instanceid}",consumes="application/json", produces="application/json")
    @ResponseBody
    public ResponseEntity<ResponseDto> findTaskHisByExtId(HttpServletRequest request, @PathVariable("instanceid") String instanceid,@RequestParam String request_json) {
        Map resMap=new LinkedHashMap();
        List<HistoricTaskInstance> his = historyService .createHistoricTaskInstanceQuery().processInstanceId(instanceid).orderByDueDateNullsLast().asc().list();
        for (HistoricTaskInstance h:his ) {   //去重处理
            resMap.put(h.getTaskDefinitionKey(),h);
        }

        return new ResponseEntity<>( ResponseDto.responseOK(resMap), HttpStatus.OK);
    }

    /**
     * 根据执行实例id 查询所有的历史处理任务节点  （此功能在处理详情页调用）
     * @param request
     * @param instanceid
     * @param request_json
     * @return
     */
    @RequestMapping(method = RequestMethod.POST,value = "doBack/{instanceid}",consumes="application/json", produces="application/json")
    @ResponseBody
    public ResponseEntity<ResponseDto> doBack(HttpServletRequest request, @PathVariable("instanceid") String instanceid,@RequestParam String request_json) {
        String logJson = request.getParameter("request_json");
        LogUtil.info(logger, "接口参数:{}", logJson);
        LoginUserVo loginUserVo = (LoginUserVo) JsonEntityTransform.json2Object(logJson, LoginUserVo.class);
        TaskBackInfoRequest backInfoRequest = (TaskBackInfoRequest) JsonEntityTransform.json2Object(logJson, TaskBackInfoRequest.class);

        if (backInfoRequest.getNowTaskId() == null || "".equals(backInfoRequest.getNowTaskId())) {
            return new ResponseEntity<>(ResponseDto.responseFail("当前节点不能为空"), HttpStatus.OK);
        }
        if (backInfoRequest.getBackTaskKey() == null || "".equals(backInfoRequest.getBackTaskKey())) {
            return new ResponseEntity<>(ResponseDto.responseFail("回退节点不能为空"), HttpStatus.OK);
        }
        if (backInfoRequest.getBackTaskUserId() == null|| "".equals(backInfoRequest.getBackTaskKey()) ) {
            return new ResponseEntity<>(ResponseDto.responseFail("回退处理人id不能为空"), HttpStatus.OK);
        }



        Task nowTask = taskservice.createTaskQuery().processInstanceId(instanceid).taskId(backInfoRequest.getNowTaskId()).singleResult();

        activitiService.turnTransition(backInfoRequest.getNowTaskId(), backInfoRequest.getBackTaskKey(), new HashMap<String, Object>());

        //保存当前节点处理意见
        TabLeaveDealMindEntity record=new TabLeaveDealMindEntity();

        record.setTaskName(nowTask.getName());
        record.setTaskId(nowTask.getId());
        record.setCreateDate(new Date());
        record.setDealUserid(loginUserVo.getUserId());
        record.setStatus("1");  //有效
        record.setIsAgree("0"); //不同意
        record.setExecutionId(nowTask.getExecutionId());
        record.setDealMindInfo(backInfoRequest.getDealMindInfo());
        leaveDealMindService.insertSelective(record);

        // 查询指定环节实例信息
        Task task = taskservice.createTaskQuery().processInstanceId(instanceid).taskDefinitionKey( backInfoRequest.getBackTaskKey()).singleResult();

        //指定回退任务处理人
        taskservice.setAssignee(task.getId(),backInfoRequest.getBackTaskUserId());

        return new ResponseEntity<>( ResponseDto.responseOK("回退成功"), HttpStatus.OK);
    }

    /**
     * 转换状态
     * @param livelist
     */
    public void getConvertStatus(List<? extends TabLeaveBillInfoEntity> livelist){
        for (TabLeaveBillInfoEntity obj : livelist) {
            obj.setConvertStatus("y");
        }
    }




    /**
     * 获取当前任务节点的办理人
     * @param executionId
     * @return
     */
    private String getCurrentUserNameByExecutionId(String executionId){
        List<Task> task = taskservice.createTaskQuery().processDefinitionKey(ProcessFlowEnum.Leave.getCode()).executionId(executionId).listPage(0,99999);
        if(!Check.isNullCollection(task)){
            String assignee = task.get(task.size()-1).getAssignee();
            TabCoreUserEntity userEntity = getUserInfos(Integer.valueOf(assignee));
            return userEntity.getUserName();
        }
        return "";
    }

    /**
     * 获取用户信息
     * @param userId
     * @return
     */
    public TabCoreUserEntity getUserInfos(Integer userId){
        return userService.getUserInfoByUserId(userId);
    }

    /**
     * 获取部门信息
     * @param orgId
     * @return
     */
    public TabCoreOrgEntity getOrgInfos(Integer orgId) {
        return orgService.selectById(orgId);
    }

}
